var ws;
var receiveId = "";
var me = "";
var userId;

function showTable(userName, id) {
    // var text = $(this).find("p").text()
    login(userName);
    receiveId = id;
    $(".chatbar-messages").css({
        "transform": "translate3d(0, 0, 0)"
    });
    $('.messages-title h4').text(userName);
    var messages_text = $(".messages-text").empty();
    //将聊天记录显示出来

    $.ajax({
        type: 'POST',
        timeout: 500,
        url: "/chat/findHistoryInfo",
        data: {id: id},
        success: function (data) {
            if (data.data != "undefined" && data.data != '') {
                $.each(data.data, function (i, chat) {
                    var message = chat.message;
                    var name = $(".messages-title").find("h4").text();
                    // var name = chat.receiverName;
                    var messages_text = $(".messages-text");
                    var timer = chat.time;
                    var sender = chat.senderName;
                    if (chat.receiver == id) {
                        let str = "<ul class='messages-text-uls'><li class='messages-text-lis2'>"
                            + "<h4><i></i><span style='position: relative;left: 140px'>" + sender + "</span><span class='time' style='position: relative;left: -50px'>"
                            + timer + "</span></h4>" + "<p>" + message + "</p>"
                            + "</ul></li>";
                        messages_text.append(str);
                    } else {
                        let str = "<ul class='messages-text-uls'><li class='messages-text-lis'>"
                            + "<h4><i></i><span>" + sender + "</span><span class='time'>"
                            + timer + "</span></h4>" + "<p>" + message + "</p>"
                            + "</ul></li>";
                        messages_text.append(str);
                    }
                })
            } else {
                messages_text.empty();
            }
        }
    })
    let div = document.getElementById("messages-text");
    div.scrollTop = div.scrollHeight;
};

//点击按钮下拉
$("#pullDown").on('click', function () {
    if ($(".chatbar").is(":visible")) {
        $(".chatbar").slideUp();
        $(".icon-box").removeClass('shadow');
    } else {
        $(".chatbar").slideDown();
        $(".icon-box").addClass('shadow');
    }
});

$(".chatbar-contacts-uls li").click(function () {
    var text = $(this).find('p').text();
    $(".chatbar-messages").css({
        "transform": "translate3d(0, 0, 0)"
    });
    $('.messages-title h4').text(text);

});

$(".return-icon").click(function () {
    $(".chatbar-contacts-uls").empty();
    findUser()
    noReadCount()
    $(".chatbar-messages").css({
        "transform": "translate3d(100%, 0, 0)"
    });
});

//发送消息
$(".message-btn").on('click', function () {
    send();
});

//开始视频通话
$(".video-btn").on('click', function () {
    // let url = "chat/vedio3.html?receiver="+receiveId;
    let url = "https://www.333blog.top/templates/chat/vedio3.html?receiver="+receiveId;
    // let url = "../chat/vedio3.html?receiver="+receiveId;
    window.open(url);
});

function send() {
    var message = $('.messages-content').val();
    // var name = $(".messages-title").find("h4").text();
    var messages_text = $(".messages-text");
    var timer = time();
    $(".messages-content").val('');
    if (message != "undefined" && message != '') {
        var str = "<ul class='messages-text-uls'><li class='messages-text-lis2'>"
            + "<h4><i></i><span style='position: relative;left: 140px'>" + name + "</span><span class='time' style='position: relative;left: -50px'>"
            + timer + "</span></h4>" + "<p>" + message + "</p>"
            + "</ul></li>";
        messages_text.append(str);
    } else {
        var messageTooltip = "<div class='message-tooltip'>不能发送空白信息</div>";
        $("body").append(messageTooltip);
        setTimeout(function () {
            $(".message-tooltip").hide();
        }, 2000);
    }
    let div = document.getElementById("messages-text");
    div.scrollTop = div.scrollHeight;
    sendMsg(receiveId, message);
}

//发送消息同步到数据库
function sendMsg(receiveId, message) {
    var msg = {
        receiveId: receiveId,
        message: message
    }
    $.ajax({
        type: 'POST',
        timeout: 500,
        url: "/chat/saveMsg",
        data: msg,
        success: function (data) {
            if (data.code == 200) {

            } else {
                alert(data.data)
            }
        }
    })
}

//时间封装
function time(type) {
    type = type || 'hh:mm'
    var timer = new Date();
    var year = timer.getFullYear();
    var month = timer.getMonth() + 1;
    var date = timer.getDate();
    var hour = timer.getHours();
    var min = timer.getMinutes();
    if (type == 'hh:mm') {
        hour = hour < 10 ? ('0' + hour) : hour;
        min = min < 10 ? ('0' + min) : min;
    }
    var time = year + "/" + month + "/" + date + "  " + hour + ":" + min;
    return time;
}

//搜索功能
$('.search-text').on('keyup', function () {
    var txt = $('.search-text').val();
    txt = txt.replace(/\s/g, '');
    $('.chatbar-contacts-uls li').each(function () {
        if (!$(this).is(':contains(' + txt + ')')) {
            $(this).hide();
        } else {
            $(this).show();
        }
    });
    return false;
});

$(function () {
    findUser();
});

function findUser() {
    $.getJSON("/api/user/findUser", function (data) {
        let html = "";
        for (var i = 0; i < data.length; i++) {
            if (data[i].noRead == "0") {
                html += "<li onclick='showTable(\"" + data[i].name + "\",\"" + data[i].id + "\")'>" + "<i class='iconfont'>&#xe752;</i>" + "<p style='position: relative;top: 8px'>" + data[i].name + "</p></li>";
            } else {
                html += "<li onclick='showTable(\"" + data[i].name + "\",\"" + data[i].id + "\")'>" + "<i class='iconfont'>&#xe752;</i>" + "<p style='position: relative;top: 8px'>" + data[i].name + "</p>" + "<i style='position: absolute;left: 200px'><font color='red' size='5px'>" + data[i].noRead + "</font></i></li>";
            }
        }
        $(".chatbar-contacts-uls").html(html);
    })
}


function login(userName) {
    var messages_text = $(".messages-text");
    if (!ws) {
        try {
            // ws = new WebSocket("ws://59.110.41.12:8080/websocket/" + name);//连接服务器
            // ws = new WebSocket("ws://127.0.0.1:8083/websocket/" + name);//连接服务器
            ws = new WebSocket("wss://www.333blog.top/websocket/" + name);//连接服务器
            ws.onopen = function (event) {
                console.log("已经与服务器建立了连接...");
            };
            ws.onmessage = function (event) {
                let d = JSON.parse(event.data);
                // if (d.message != null){
                //     return;
                // }
                if (d.message == "1") {
                    return;
                }
                // alert("收到服务器信息")
                // console.log("接收到服务器发送的数据..." + d);
                if (d.type == 1) return;
                let str = "<ul class='messages-text-uls'><li class='messages-text-lis'>"
                    + "<h4><i></i><span>" + userName + "</span><span class='time'>"
                    + "刚刚" + "</span></h4>" + "<p>" + d.data + "</p>"
                    + "</ul></li>";
                messages_text.append(str);
                let div = document.getElementById("messages-text");
                div.scrollTop = div.scrollHeight;
            };
            ws.onclose = function (event) {
                console.log("已经与服务器断开连接...");
            };
            ws.onerror = function (event) {
                console.log("WebSocket异常！");
            };
        } catch (ex) {
            alert(ex.message);
        }
        // document.getElementById("login").innerHTML = "退出";
    } else {
        ws.close();
        ws = null;
    }
}


// function SendData(message) {
//     try {
//         ws.send(message);
//     } catch (ex) {
//         alert(ex.message);
//     }
// };